package design.simdi.code.final_paper.site.panels.proiecte.bibliografie;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.wicket.extensions.markup.html.repeater.util.SortParam;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.injection.web.InjectorHolder;
import org.apache.wicket.model.IModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import design.simdi.code.final_paper.core.daos.BibliographyDao;
import design.simdi.code.final_paper.core.entities.Bibliography;

/**
 * 
 * @author Marius Dumitriu - (Jun 21, 2010 - 3:45:39 PM)
 * 
 */
public class SortableBibliographyDataProvider extends SortableDataProvider<Bibliography> {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@SpringBean
	private BibliographyDao bibliographyDao;

	private List<Criterion> criterii;

	/**
	 * constructor
	 */
	public SortableBibliographyDataProvider() {
		InjectorHolder.getInjector().inject(this);
		// set default sort
		setSort("name", true);
		criterii = new ArrayList<Criterion>();
		criterii.add(Restrictions.isNotNull("person"));

	}

	/**
	 * @see org.apache.wicket.markup.repeater.data.IDataProvider#iterator(int,
	 *      int)
	 */
	public Iterator<Bibliography> iterator(int first, int count) {
		SortParam sp = getSort();
		Order o;
		if (sp.isAscending())
			o = Order.asc(sp.getProperty());
		else
			o = Order.desc(sp.getProperty());

		return bibliographyDao.findAll(new Order[] { o }, criterii).subList(first, first + count).iterator();

	}

	/**
	 * @see org.apache.wicket.markup.repeater.data.IDataProvider#size()
	 */
	public int size() {
		return bibliographyDao.findAll(new Order[] {}, criterii).size();
	}

	/**
	 * @see org.apache.wicket.markup.repeater.data.IDataProvider#model(java.lang.Object)
	 */
	public IModel<Bibliography> model(Bibliography object) {
		return new DetachableBibliographyModel(object, bibliographyDao);
	}

	public void setCriterii(List<Criterion> criterii) {
		this.criterii = criterii;
	}

	public List<Criterion> getCriterii() {
		return criterii;
	}

	public void setBibliographyDao(BibliographyDao BibliographyDao) {
		this.bibliographyDao = BibliographyDao;
	}

	public BibliographyDao getBibliographyDao() {
		return bibliographyDao;
	}

}